<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\express\OrderAddress;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Loader;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    public function index()
    {
       /* p($this->auth->getUserInfo());
        p($_SESSION);die;*/
        $admin_user = $this->auth->getUserInfo();

        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)->where(['spid'=>$admin_user['id']])
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        $admin_user = $this->auth->getUserInfo();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['spid'] = $admin_user['id'];
            $orderSn = \app\admin\model\Order::getOrderSn();
            $params['orderSn'] = $orderSn;
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("from_address",$admin_user['from_address']);
        $this->view->assign("from_mobile",$admin_user['from_mobile']);
        $this->view->assign("from_username",$admin_user['from_username']);

        return $this->view->fetch();
    }

    /**
     * 打印PDF
     */
    public function print($ids = null){
        Loader::import('tcpdf.tcpdf', EXTEND_PATH);
        // create new PDF document
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Nicola Asuni');
        $pdf->SetTitle(date('Y-m-d').'-'.time());
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// remove default header/footer
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);

// set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

// set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);


        // ---------------------------------------------------------

        // set font
        $pdf->SetFont('stsongstdlight', 'B', 15);
        $pdf->SetFont('times', 'B', 15);
        // 查询包裹
        $orderList = model('app\admin\model\Order')
            ->where('id','in',$ids)
            ->select();
        // 循环包裹插入pdf
        foreach ($orderList as $order){
            // add a page
            $pdf->AddPage();
            $pdf->setJPEGQuality(75);
            $style = array(
                'position' => 'absolute',
                'align' => 'R',
                'stretch' => true,
                'fitwidth' => true,
                'cellfitalign' => '',
                'border' => false,
                'hpadding' => 'auto',
                'vpadding' => 'auto',
                'fgcolor' => array(0,0,0),
                'bgcolor' => false, //array(255,255,255),
                'text' => true,
                'font' => 'helvetica',
                'fontsize' => 12,
                'stretchtext' => 4
            );

            //条形码
            $pdf->write1DBarcode($order['orderSn'], 'C128', '120', '', '', 30, 0.9, $style, 'R');
            //换行
            $pdf->Ln();
            $pdf->Cell(30, 20,"FROM:", 'T', 0, 'L', 0); //border:T顶部，L左边，R右边，B底部   align:L文字在左边，R右边，C中间
            $pdf->Ln();
            $pdf->Cell(100, 20, 'Name:'.$order['from_username'], 'TR', 0, 'L', 0);
            $pdf->Cell(80, 20, 'Tel:'.$order['from_mobile'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(140, 20, 'Address:'.$order['from_address'], 'TR', 'L', '', 0);
            $pdf->Cell(40, 30, 'Weight:'.$order['weight'], 'LT', 'L', '', 0);
            $pdf->Ln();
            $pdf->Cell(30, 20,"TO:", 'T', 0, 'L', 0);
            $pdf->Cell(150, 20,"", 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->Cell(100, 20, 'Name:'.$order['username'], 'TR', 0, 'L', 0);
            $pdf->Cell(80, 20, 'Tel:'.$order['mobile'], 'T', 0, 'L', 0);
            $pdf->Ln();
            $pdf->MultiCell(180, 20, 'Address:'.$order['address'], 'T', 'L', '', 0);
        }


        //Close and output PDF document
        $pdf->Output(date('Y-m-d').'-'.time(), 'I');
        exit;
    }

    public function address(){
        if ($this->request->isPost()) {
            $this->token();
        }
        $admin_user = $this->auth->getUserInfo();
        $admin_id = $admin_user['id'];
        $model = new Admin();
        $row = $model->get($admin_id);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success("success");
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
